package services;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import tags.Tag;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.google.wave.api.Blip;
import com.google.wave.api.ElementType;
import com.google.wave.api.FormElement;
import com.google.wave.api.Gadget;
import com.google.wave.api.Range;
import com.google.wave.api.StyleType;
import com.google.wave.api.StyledText;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;

import datastore.Contact;

public class ParrotyService {
	
	private static final String STRINGEMPTY = "";
	private static final String ALERTGADGET = "http://gadgets-pa.googlecode.com/svn/trunk/%20gadgets-pa/AJAX/alertGadget.xml";
	private final static String URLOFGADGETTAGS = "http://gadgets-pa.googlecode.com/svn/trunk/%20gadgets-pa/tag/tagsAndParticipants.xml";
	private final static String ADDPARTICIPANT = "http://gadgets-pa.googlecode.com/svn/trunk/%20gadgets-pa/AJAX/addParticipant.xml";
	private static final String STRINGSIZE = "size";
	
	private TagParticipantService tagParticipantService;
	private static final DBService dbService = new DBService();

	
	public ParrotyService(TagParticipantService tagParticipantService) {
		this.tagParticipantService = tagParticipantService;
	}
	
	public Gadget getGadgetByUrl(Blip blip,String urlOfGadget){
		return blip.getDocument().getGadgetView().getGadget(urlOfGadget);
	}
	
	public void addParticipant(TextView textView){
		FormElement fe = new FormElement(ElementType.BUTTON, "Add a participant", "Add a participant");    	
    	textView.appendElement(new Gadget(ADDPARTICIPANT));
    	textView.appendElement(fe);
	}
	
	
	 
	 private Gadget setTagToGadget(Gadget gadget){
		 
		 Tag [] tags = Tag.values();				
		 gadget.setField(STRINGSIZE,(new Integer(tags.length)).toString());
		 Integer i = new Integer(0);
		 for(Tag tag : tags){
			 gadget.setField(i.toString(), tag.toString());
			 i++;
		 }
		 
		 return gadget;
	 }
	 
	 // TODO
	 private String getParentTags(String parentId,Map<String,String> dataOfWavlet){
		 String parentTags = "";
		 
		 if(parentId == null) return parentTags;
		 
		 parentTags = dataOfWavlet.get(parentId);
		 
		 if(parentTags == null) return "";
//		 System.out.println(parentTags);
		 return parentTags;
		 
			 
	 }
	 
	 // TODO
	 public void insertTagGadget(Blip blip,Wavelet wavelet,String modifyBy){
		 	TextView textView = blip.getDocument();
		 	Gadget gadget = textView.getGadgetView().getGadget(URLOFGADGETTAGS);
		 	if(gadget == null){
		 		gadget = new Gadget(URLOFGADGETTAGS);
//		 		System.out.println(blip.getParentBlipId());
		 		for(String participant : wavelet.getParticipants()){
			 		String value =  getParentTags( participant + "_" + blip.getParentBlipId(),wavelet.getDataDocuments());
			 		if(!value.equals("")){		
			 			gadget.setField(participant, value);
			 		}
			 		
			 		wavelet.setDataDocument(participant + "_" + blip.getBlipId(), value);
			 		
		 		}
//		 		System.out.println(blip.getBlipId());
		 		
		 		textView.insertElement(0,setTagToGadget(gadget));
		 		
	 		}
	 }

	
	public void setTagToWaveletDataDocument(Wavelet wavelet, Blip blip, String modifiedBy ){
		Gadget gadget = getGadgetByUrl(blip, URLOFGADGETTAGS);
		String tag = "";
    	if(gadget != null && null != (tag = gadget.getField(modifiedBy))){
    		
    		//System.out.println(wavelet.getDataDocument(e.getBlip().getBlipId()));
    		
    		//System.out.println(wavelet.getDataDocuments().size());
    		//printMap(wavelet.getDataDocuments());

    	
    		String tagsInBlip = wavelet.getDataDocument(modifiedBy + "_" + blip.getBlipId());
    		
    		boolean setTag = true;
    		if(tagsInBlip != null){
    			setTag = !tagsInBlip.equals(tag);
    		}
    		
    		if(setTag){
    			tagsInBlip = gadget.getField(modifiedBy);	    			 	    		
    			System.out.println(tagsInBlip);
    			wavelet.setDataDocument(modifiedBy + "_" + blip.getBlipId(),tagsInBlip);
    			//System.out.println(wavelet.getDataDocuments().size());
    			//String [] strArray = tagsInBlip.split(" ");
    			//storeToDatabase(e.getBlip(),strArray[strArray.length - 1],-1,-1,e.getBlip().getBlipId());
    			//printMap(wavelet.getDataDocuments());
    		}
    	}
	}
	
	public void setMessagesFromGadgetToBlip(Blip blip,TextView textView,String modifiedBy){
		Gadget gadget = getGadgetByUrl(blip, URLOFGADGETTAGS);
    	String text = "";
    	if(gadget != null && null != (text = gadget.getField(modifiedBy + "_messages" ))){
    		if(textView.getText().indexOf(text) == -1){	// not add the same text, setField by gadget is not use    			
//    			textView.setAnnotation("style/fontWeight", "style/fontWeight=bold");
//    			textView.setAnnotation("style/fontSize", "style/fontWeight=bold");
    			textView.appendStyledText(new StyledText(text, StyleType.HEADING2));
//    			textView.setAnnotation(new Range(0,text.length()),"style/fontWeight", "style/fontWeight=bold");
//    			textView.setAnnotation(new Range(0,text.length()),"style/fontSize", "style/fontWeight=bold");
    			
    		}	    		
    	}
	}
	
	public void isAlertGadgetInBlipThanDeleteIt(Blip blip, TextView textView){
		Gadget gadget = getGadgetByUrl(blip, ALERTGADGET);
    	
    	if(gadget != null){
    		if(gadget.getField("delete") != null){
    			textView.getGadgetView().delete(gadget);
    		}
    	}
	}
	
	/*
	 * add Participant to wavlet
	 * email - for testing, i suppose that google email address is the same as wave account. -> replace gmail.com to googlewave.com 
	 */
	public void addParticipantToWavelet(Gadget gadget, Wavelet wavelet, String email,String modifiedBy){
		
		if(email != null && !email.equals(STRINGEMPTY)){
				String hasAddParticipant = STRINGEMPTY;

					try {
						hasAddParticipant = tagParticipantService.hasAddParticipant(modifiedBy.replace("googlewave.com","gmail.com"),email, wavelet.getDataDocuments());
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (ServiceException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
				
			if(hasAddParticipant.equals(STRINGEMPTY)){
				
				if(email.indexOf("gmail.com") != -1){
					
					email = email.replace("gmail.com", "googlewave.com");
					
				}
				System.out.println("add user");
			     wavelet.addParticipant(email);
			}else{
				Gadget alertGadget = new Gadget(ALERTGADGET);
				// alertGadget.setField(modifiedBy, "Content is not enabled for the particapant, content contains tags: " + hasAddParticipant );
				alertGadget.setField(modifiedBy, "Conflict detected! Cannot add user Carol to the conversation. User Carol is not supposed to see any conversation annotated with the following tags: " + hasAddParticipant );
				wavelet.getRootBlip().getDocument().appendElement(alertGadget);
			}
			
			}else{
				System.out.println("Email is null");
			}
			
			
		
	}
	
	 private void printMap(Map map){
		 
		 Set<Entry<String, String>> entries = map.entrySet();

		 for (Entry entry : entries) {
		   System.out.println((String) entry.getKey());
		   System.out.println((String) entry.getValue());
		 }

	 }

	 private String getPassword(String name) throws AuthenticationException{
			Contact contact = dbService.getContact(name);
			return contact.getPassword();
			
		}
	
}
